defmodule EliPhxPlayWeb.CounterLive do
  use EliPhxPlayWeb, :live_view

  # 初始状态
  def mount(_params, _session, socket) do
    {:ok, assign(socket, count: 0, message: "欢迎来到实时计数器！")}
  end

  # 渲染界面
  def render(assigns) do
    ~H"""
    <div class="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-lg">
      <h1 class="text-3xl font-bold text-center mb-6 text-blue-600">
        🎯 LiveView 计数器
      </h1>
      
      <div class="text-center mb-6">
        <p class="text-gray-600 mb-2"><%= @message %></p>
        <div class="text-6xl font-bold text-green-500 mb-4">
          <%= @count %>
        </div>
      </div>
      
      <div class="flex justify-center space-x-4">
        <button 
          phx-click="increment" 
          class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded transition-colors"
        >
          ➕ 加1
        </button>
        
        <button 
          phx-click="decrement" 
          class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded transition-colors"
        >
          ➖ 减1
        </button>
        
        <button 
          phx-click="reset" 
          class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded transition-colors"
        >
          🔄 重置
        </button>
      </div>
      
      <div class="mt-6 text-center">
        <p class="text-sm text-gray-500">
          实时更新，无需刷新页面！⚡
        </p>
      </div>
    </div>
    """
  end

  # 处理事件
  def handle_event("increment", _params, socket) do
    new_count = socket.assigns.count + 1
    message = if new_count == 10, do: "🎉 恭喜达到10！", else: "继续点击试试！"
    
    {:noreply, assign(socket, count: new_count, message: message)}
  end

  def handle_event("decrement", _params, socket) do
    new_count = max(0, socket.assigns.count - 1)
    message = if new_count == 0, do: "已经到底了！", else: "还能继续减少"
    
    {:noreply, assign(socket, count: new_count, message: message)}
  end

  def handle_event("reset", _params, socket) do
    {:noreply, assign(socket, count: 0, message: "重新开始！")}
  end
end

